import { http } from '/@/utils/http';
import type { AxiosProgressEvent } from '/@/utils/http';
import { ContentTypeEnum } from '/@/enums/httpEnum';
import type {
  UploadImageParams,
  UploadNextParams,
  UploadResultModel,
  UploadImageResultModel,
} from './model/commonModel';
import { uuid } from '/@/utils/uuid';

export function upload() {
  return http.post<UploadResultModel>({
    url: '/api/app/base/comm/upload',
  });
}

export function next(
  params: UploadNextParams,
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void,
  signal?: AbortSignal,
) {
  return http.post(
    {
      url: params.host,
      headers: {
        'Content-Type': ContentTypeEnum.FORM_DATA,
      },
      params: params.data,
      onUploadProgress,
      signal,
    },
    {
      isReturnNativeResponse: true,
    },
  );
}

/**
 * 上传图片
 * @param params UploadImageParams
 * @returns UploadImageResultModel
 */
export async function uploadImage(
  params: UploadImageParams,
  onUploadProgress?: (progressEvent: AxiosProgressEvent) => void,
  signal?: AbortSignal,
): Promise<UploadImageResultModel> {
  const res = await upload();
  const fileId = uuid();
  const fileName = [params.prefixPath, fileId + '_' + (params.filename || params.file.name)]
    .filter(Boolean)
    .join('/');
  await next(
    {
      host: res.host,
      data: {
        key: fileName,
        OSSAccessKeyId: res.OSSAccessKeyId,
        policy: res.policy,
        signature: res.signature,
        file: params.file,
      },
    },
    onUploadProgress,
    signal,
  );
  return {
    url: `${res.host}/${fileName}`,
    alt: fileName,
    href: `${res.host}/${fileName}`,
  };
}
